package studio.raptor.ddal.core.log;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import studio.raptor.ddal.core.log.bo.SqlProcessLogData;
import studio.raptor.ddal.core.log.common.CommonMethodUtil;
import studio.raptor.ddal.core.log.queue.IQueueHelper;

import java.io.*;
import java.util.Properties;
import java.util.UUID;

/**
 * 异步批量处理日志
 */
public class AsyncBatchLog implements Runnable{

	private static Logger logger = LoggerFactory.getLogger(AsyncBatchLog.class);

	private boolean runFlag = true;
    private String address;
    private int timeout;
    private String appName;
    private IQueueHelper queueHelper;
    private String logType;

	public AsyncBatchLog(String address,int timeout,String appName, IQueueHelper queueHelper, String logType){
		this.address = address;
		this.timeout = timeout;
		this.appName = appName;
		this.queueHelper = queueHelper;
		this.logType = logType;
	}

	/**
	 * 发送日志处理，如果队列为空，则阻塞
	 */
	public void run() {
        while(runFlag){
    		try{
				Object logObj = queueHelper.readObj(logType);
				logger.debug("AsyncBatchLog 从队列读出对象并发送给后端服务 "+ logObj.toString());
    			String result = LogHttpClient.sendObj(address,timeout, logObj,appName);
				logger.debug("==========="+result);
			}catch(Exception e){
				logger.error("AsyncBatchLog:send logObj error",e);
    		}
    	}
    	if(!runFlag){
        	//休息2分钟后再扫描
			CommonMethodUtil.waitSleep(120000);
		}
    }

	public IQueueHelper getQueueHelper() {
		return queueHelper;
	}
	public void setQueueHelper(IQueueHelper queueHelper) {
		this.queueHelper = queueHelper;
	}

	public boolean isRunFlag() {
		return runFlag;
	}

	public void setRunFlag(boolean runFlag) {
		this.runFlag = runFlag;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public int getTimeout() {
		return timeout;
	}

	public void setTimeout(int timeout) {
		this.timeout = timeout;
	}

	/**
	 * 对象转换成字符串
	 * @param obj
	 * @return
	 * @throws IOException
	 */
	public static String ObjtoStr(Object obj) throws IOException{
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		ObjectOutputStream oos = new ObjectOutputStream(out);
		oos.writeObject(obj);
		byte[] objstr = out.toByteArray();
		return new String(objstr);
	}

	public static void main(String[] args) throws Exception {

		Properties systemProperties = new Properties();
		try {
			systemProperties.load(AsyncBatchLog.class.getResourceAsStream("/ddal/system.properties"));
		} catch (IOException ioe) {
			logger.error("load /ddal/system.properties file failed.", ioe);
		}
		String logSwitch = systemProperties.getProperty( "log.server.switch" );
		String appName = systemProperties.getProperty( "log.server.app.name" );
		String address = systemProperties.getProperty( "log.server.url" );
		int timeout = Integer.parseInt(systemProperties.getProperty( "log.server.timeout" ).trim());
		int threadNum = Integer.parseInt(systemProperties.getProperty( "log.thread.num" ).trim());
		int queueDepth = Integer.parseInt(systemProperties.getProperty( "log.queue.depth" ).trim());
		System.out.println( "AsyncBatchLog.main logSwitch="+logSwitch );
		System.out.println( "AsyncBatchLog.main address="+address );

		SqlProcessLogData sqlLogData=new SqlProcessLogData(  );
		sqlLogData.setTraceId( UUID.randomUUID().toString() );

		String str = ObjtoStr(sqlLogData);
		System.out.println(str);

		ByteArrayInputStream byteIn = new ByteArrayInputStream(str.getBytes());
		ObjectInputStream in = new ObjectInputStream(byteIn);
		SqlProcessLogData sqlData = (SqlProcessLogData) in.readObject();
		System.out.println(sqlData.getTraceId());
	}

}